package com.kws.merchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.security.auth.AuthUtil;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.merchant.domain.AttentionEntity;
import com.kws.merchant.domain.Device;
import com.kws.merchant.domain.Serve;
import com.kws.merchant.domain.ShopCartEntity;
import com.kws.merchant.domain.po.DevicePo;
import com.kws.merchant.domain.po.ShopCartPo;
import com.kws.merchant.domain.vo.ShopCartVo;
import com.kws.merchant.mapper.ShopCartMapper;
import com.kws.merchant.service.AttentionService;
import com.kws.merchant.service.DeviceService;
import com.kws.merchant.service.ServeService;
import com.kws.merchant.service.ShopCartService;
import com.kws.merchant.util.FileUtil;
import com.kws.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : zhangbenting
 * @date : 2024/10/31 20:07
 * @Version: 1.0
 */
@Service
public class ShopCartServiceImpl extends ServiceImpl<ShopCartMapper, ShopCartEntity> implements ShopCartService {

    @Value("${minio.ENDPOINT}")
    private String minioUrl;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ServeService serveService;
    @Autowired
    private AttentionService attentionService;


    @Override
    public Page<ShopCartVo> getShopCartList(ShopCartPo shopCartPo) {
        shopCartPo.setPageSize((shopCartPo.getPageSize() - 1) * shopCartPo.getTotalPage());
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        List<AttentionEntity> attentionEntityList = attentionService.list(Wrappers.<AttentionEntity>lambdaQuery().eq(AttentionEntity::getUserId, userId));
        Map<String, List<AttentionEntity>> attentionMap = attentionEntityList.stream().collect(Collectors.groupingBy(AttentionEntity::getType));
        if (shopCartPo.getGoodsType().equals(1)) {
            long count = this.count(Wrappers.<ShopCartEntity>lambdaQuery().eq(ShopCartEntity::getUserId,
                    userId).eq(ShopCartEntity::getType, 1));
            Page<ShopCartVo> shopCartEntityPage = new Page<>(shopCartPo.getTotalPage(), shopCartPo.getPageSize(), count);
            if (count > 0) {
                List<ShopCartVo> shopCartList = baseMapper.getServeShopCartList(userId,
                        shopCartPo.getPageSize(), shopCartPo.getTotalPage());
                List<AttentionEntity> attentionList = attentionMap.get("1");
                for (ShopCartVo shopCartVo : shopCartList) {
                    shopCartVo.setShowImg(FileUtil.fixFileName() + shopCartVo.getImg());
                    shopCartVo.setGoodsType(1);
                    if (attentionList != null && attentionList.size() > 0) {
                        List<AttentionEntity> entities = attentionList.stream().filter(p -> p.getAttentionTypeId().equals(shopCartVo.getGoodsId())).collect(Collectors.toList());
                        if (entities != null && entities.size() > 0) {
                            shopCartVo.setIsCollect(true);
                        } else {
                            shopCartVo.setIsCollect(false);
                        }
                    }else {
                        shopCartVo.setIsCollect(false);
                    }
                }
                shopCartEntityPage.setRecords(shopCartList);
                return shopCartEntityPage;
            }
        } else {
            long count = this.count(Wrappers.<ShopCartEntity>lambdaQuery().eq(ShopCartEntity::getUserId,
                    userId).eq(ShopCartEntity::getType, 0));
            Page<ShopCartVo> shopCartEntityPage = new Page<>(shopCartPo.getTotalPage(), shopCartPo.getPageSize(), count);
            if (count > 0) {
                List<ShopCartVo> shopCartList = baseMapper.getDeviceShopCartList(userId,
                        shopCartPo.getPageSize(), shopCartPo.getTotalPage());
                List<AttentionEntity> attentionList = attentionMap.get("0");
                for (ShopCartVo shopCartVo : shopCartList) {
                    if (attentionList != null && attentionList.size() > 0) {
                        List<AttentionEntity> entities = attentionList.stream().filter(p -> p.getAttentionTypeId().equals(shopCartVo.getGoodsId())).collect(Collectors.toList());
                        if (entities != null && entities.size() > 0) {
                            shopCartVo.setIsCollect(true);
                        } else {
                            shopCartVo.setIsCollect(false);
                        }
                    }else {
                        shopCartVo.setIsCollect(false);
                    }
                    if (ObjectUtils.isNotNull(shopCartVo.getSpecificationId())) {
                        shopCartVo.setShowImg(FileUtil.fixFileName() + shopCartVo.getSpecificationImg());
                    } else {
                        shopCartVo.setShowImg(FileUtil.fixFileName() + shopCartVo.getImg());
                    }
                    shopCartVo.setGoodsType(0);
                }
                shopCartEntityPage.setRecords(shopCartList);
                return shopCartEntityPage;
            }
        }
        return new Page<ShopCartVo>();
    }

    @Override
    public boolean addShopCartGoods(ShopCartPo shopCartPo) {
        if (ObjectUtils.isEmpty(shopCartPo.getGoodsId())) {
            throw new RuntimeException("请选择商品！");
        }
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        LambdaQueryWrapper<ShopCartEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ShopCartEntity::getUserId, userId);
        wrapper.eq(ShopCartEntity::getDeviceId, shopCartPo.getGoodsId());
        wrapper.eq(ShopCartEntity::getType, shopCartPo.getGoodsType());
        if (ObjectUtils.isNotNull(shopCartPo.getSpecificationId())){
            wrapper.eq(ShopCartEntity::getSpecificationId, shopCartPo.getSpecificationId());
        }
        ShopCartEntity cartEntity = this.getOne(wrapper);
        if (ObjectUtils.isNotNull(cartEntity)) {
            cartEntity.setGoodsCount(cartEntity.getGoodsCount() + shopCartPo.getGoodsCount());
            return this.updateById(cartEntity);
        }
        ShopCartEntity shopCartEntity = new ShopCartEntity();
        shopCartEntity.setDeviceId(shopCartPo.getGoodsId());
        shopCartEntity.setUserId(userId);
        shopCartEntity.setSpecificationId(shopCartPo.getSpecificationId());
        shopCartEntity.setGoodsCount(shopCartPo.getGoodsCount());
        shopCartEntity.setType(shopCartPo.getGoodsType());
        //查询商品、服务的商家id，便于后续统计购物车
        switch (shopCartPo.getGoodsType()) {
            case 0:
                Device device = deviceService.getById(shopCartPo.getGoodsId());
                if (ObjectUtils.isEmpty(device)) {
                    throw new RuntimeException("没有查询到该设备信息");
                }
                shopCartEntity.setMerchantId(device.getMerchantId());
                break;
            case 1:
                Serve serve = serveService.getById(shopCartPo.getGoodsId());
                if (ObjectUtils.isEmpty(serve)) {
                    throw new RuntimeException("没有查询到该服务信息");
                }
                shopCartEntity.setMerchantId(serve.getMerchantId());
                break;
        }
        return this.saveOrUpdate(shopCartEntity);
    }

    /**
     * 购物车加购人数
     *
     * @param userId
     * @param time
     * @return
     */
    @Override
    public Double merchantShopCartByUserAndTime(Long userId, String time) {
        return this.baseMapper.merchantShopCartByUserAndTime(userId, time);
    }

    /**
     * 总加购人数
     *
     * @param userId
     * @return
     */
    @Override
    public Double countShopCartByUser(Long userId) {
        return this.baseMapper.countShopCartByUser(userId);
    }


}
